package t4dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import t4bean.PurchaseRecordBean;
import t4jdbc.JDBCUtil;

public class PurchaseRecordDao extends Dao {
	private SetSql ss = new SetSql();

	public int insert(PurchaseRecordBean prb) {
		String sql = "insert into purchaserecord(fruitname,purchasetime,number,cost) values(?,?,?,?)";
		List<Object> list = new ArrayList<>();
		list.add(prb.getFruitName());
		list.add(prb.getPurchaseTime());
		list.add(prb.getNumber());
		list.add(prb.getCost());
		try {
			int back = dml(sql, list);
			return back;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public List<PurchaseRecordBean> select(PurchaseRecordBean prb) throws SQLException {
		String sql;
		List<Object> list = new ArrayList<>();
		if (prb != null) {
			sql = "select * from purchaserecord where ";
			sql = ss.setSql(prb, sql, list, 2);
		} else {
			sql = "select * from purchaserecord";
		}
		List<PurchaseRecordBean> backList = new ArrayList<>();
		ResultSet rs = null;
		try {
			rs = dql(sql, list);
			while (rs.next()) {
				PurchaseRecordBean prb1 = new PurchaseRecordBean();
				prb1.setFruitName(rs.getString("fruitname"));
				Timestamp tt = rs.getTimestamp("purchasetime");
				prb1.setPurchaseTime(tt.toLocalDateTime());
				prb1.setNumber(rs.getInt("number"));
				prb1.setCost(rs.getInt("cost"));
				backList.add(prb1);
			}
			return backList;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(super.conn, super.ps, super.rs);
			super.conn = null;
			super.ps = null;
			super.rs = null;
			rs.close();
			rs = null;
		}
		return null;
	}
}
